import sys
import time
import getopt
import query
import common

QUERY_MAX = 50
SMTP_HOST = "smtp.gmail.com:587"
TO_EMAIL = "jaredcrace@gmail.com"
FROM_EMAIL = "lazyListUpdate@lazylist.com"
CITY = "sanantonio"
SECTION = "sga"
QUERY = "bench"
PRICE = 200 
FREQ = 5 

           
##########################
# other functions
def extMiddle(st):
   par = st.partition(">")
#   print "extMiddle par:", par
   mid = par[2].partition("<")
#   print "extMiddle mid:", mid
#   print "ans:", mid[0].strip(" ")
#   print " "
   return mid[0].strip(" ")

def extHttp(st):
   par = st.partition("\"")
#   print "extHttp par:", par
   mid = par[2].partition("\"")
#   print "extHttp mid:", mid
#   print "ans:", mid[0].strip(" ")
#   print " "
   return mid[0].strip(" ")

def extLoc(st):
   par = st.partition("(")
#   print "extLoc par:", par
   mid = par[2].partition(")")
#   print "extLoc mid:", mid
#   print "ans:", mid[0].strip(" ")
#   print " "
   return mid[0].strip(" ")

def extId(st):
   par = st.partition(".html")
#   print "extId par:", par
   mid = par[0].split("/")
#   print "extId mid:", mid
#   print "ans:", mid[len(mid)-1]
#   print " "
   return mid[len(mid)-1]

def retMonth(s):
   if s == "Jan":
      return 1   
   if s == "Feb":
      return 2   
   if s == "Mar":
      return 3   
   if s == "Apr":
      return 4   
   if s == "May":
      return 5   
   if s == "Jun":
      return 6   
   if s == "Jul":
      return 7   
   if s == "Aug":
      return 8   
   if s == "Sep":
      return 9   
   if s == "Oct":
      return 10   
   if s == "Nov":
      return 11   
   if s == "Dec":
      return 12   

def createPost(rawPost):
   nPost = query.Post(CITY, SECTION, QUERY, PRICE)
   sp = rawPost.split("\n")
   for i in sp:
      if 'itemdate' in i:
#         print "found itemdate"
         nPost.date = extMiddle(i)
         s = nPost.date.split(" ")
         m = retMonth(s[0])
         d = s[len(s)-1]
         tStr = "2013-%s-%s" % (m,d)
         nPost.epoch = time.mktime(time.strptime(tStr, "%Y-%m-%d"))
      if 'itempp' in i:
#         print "found itempp" 
         p = extMiddle(i)
         sp = p.split("$")
         nPost.price = sp[len(sp)-1]
      if 'http' in i:
         if "itemcg" not in i:
#            print "found http"
            nPost.title = extMiddle(i)
            nPost.http = extHttp(i)
            nPost.Id = extId(nPost.http)
      if 'itempn' in i:
#         print "found itempn"
         nPost.location = extLoc(i)
      if 'pic' in i:
#         print "found pic"
         nPost.hasPic = 1

#   nPost._print()
#   raw_input("stop")
   return nPost




######################################
# main() was made to make it easier
#  to call from a debugger
######################################
def main():        
   QUERY_MAX = 50
   SMTP_HOST = "smtp.gmail.com:587"
   TO_EMAIL = "jaredcrace@gmail.com"
   FROM_EMAIL = "lazyListUpdate@lazylist.com"
   CITY = "sanantonio"
   SECTION = "sga"
   QUERY = "bench"
   PRICE = 200 
   FREQ = 5 

   try:
      opts, args = getopt.getopt(sys.argv[1:],"s:q:p:t:", 
         ["section=", "query="])
   except getopt.GetoptError:
      print "error with getopt"
      exit()

   for opt,arg in opts:
      if opt == "-s":
         SECTION = arg
      elif opt == "-q":
         QUERY = arg
      elif opt == "-p":
         PRICE = arg
      elif opt == "-t":
         FREQ = arg * 60 #converting to minutes
      else:
         assert False, "unhandled option" 

   url="http://"+CITY+".craigslist.org/search/" \
        +SECTION+"?query="+QUERY.replace(' ', ',')

   common.logMsg("url search was " + url)

   # search forever, waking up on frequency count 
   mainQuery = query.Query()
   freq_cnt = 0
   
   # get smtp username and password
   username = raw_input("Enter smtp server username:\n")
   password = raw_input("Enter smtp server password:\n")
   while(1):
      
      msg = common.requestURL(url)

      if(msg != []):
         infile = open("msg.html", "w")
         infile.write(msg)
         infile.close()
      else:
         print "Error - requestURL failed\n"
         exit()

      infile = open("msg.html", "r")
      line = infile.readline()
      rawPost = "" 
      collect = 0
      while(len(line) != 0):
         if "class=\"row\"" in line:
            collect = 1
         if "</p>" in line:
            rawPost = str(rawPost) + line
#         print "raw:", rawPost
            post = createPost(rawPost)
#         raw_input("pause")
            mainQuery.add(post)

            collect = 0

         if collect == 1:
            rawPost = str(rawPost) + line
         else:
            rawPost = []

         line = infile.readline() 

      infile.close()
    
#   mainQuery._print()
      mainQuery.emailQuery(SMTP_HOST, FROM_EMAIL, TO_EMAIL, username, password)
      common.logMsg("Query length: " + str(mainQuery.length))
      
      freq_cnt = freq_cnt + 1
      freqMsg = "sleeping, freq:%d min, freq_cnt:%d" % (FREQ, freq_cnt) 
      common.logMsg(freqMsg)
      time.sleep(FREQ)     


# determines if it is running standalone
if __name__ == "__main__":
   main()


